package com.da.auth.controller;


import com.alibaba.fastjson2.JSON;
import com.da.common.entity.PageResult;
import com.da.common.enums.ResultEnum;
import com.da.common.exception.BusinessException;
import com.da.common.exception.ParameterException;
import com.da.common.utils.DailyAimResult;
import com.da.auth.convert.DailyUserConverter;
import com.da.auth.entity.DailyUsers;
import com.da.auth.entity.dto.DailyUsersDTO;
import com.da.auth.service.DailyUserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLDataException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


/**
 * @Author: hyacinth
 * @CreateTime: 2025-01-10
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class DailyUserController {

    private final DailyUserService dailyUsersService;

    public DailyUserController(DailyUserService dailyUsersService) {
        this.dailyUsersService = dailyUsersService;
    }

    @GetMapping("/getPageByAllUsers")
    @Operation(summary = "查询所有用户", description = "查询所有用户")
    public DailyAimResult<PageResult<DailyUsers>> getPageByAllUsers(@RequestParam(defaultValue = "1") int pageNum,
                                                                    @RequestParam(defaultValue = "10") int pageSize) {
        return DailyAimResult.success(dailyUsersService.getPageByAllUsers(pageNum, pageSize));
    }


    @GetMapping("/{id}")
    @Operation(summary = "通过id查询用户", description = "通过id查询用户")
    public DailyAimResult<DailyUsers> getUserById(@PathVariable String id) throws ParameterException, SQLDataException {
        log.info("接收到的id为:{}", id);
        Optional.ofNullable(id).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "id为空"));
        DailyUsers user = dailyUsersService.getUserById(id);
        return user != null ? DailyAimResult.success("查询用户成功", user) : DailyAimResult.error(ResultEnum.FAIL.getCode(), "");
    }

    @PostMapping("/createUser")
    @Operation(summary = "注册用户", description = "注册用户")
    public DailyAimResult<Boolean> createUser(@RequestBody DailyUsersDTO dailyUsersDTO) throws Exception {
        log.info("接口接收到的dailyUsersDTO对象:" + JSON.toJSONString(dailyUsersDTO));
        Optional.ofNullable(dailyUsersDTO).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "dailyUsersDTO对象为空"));

        Boolean isCreateUser = dailyUsersService.createUser(dailyUsersDTO);
        if (isCreateUser) {
            return DailyAimResult.success(ResultEnum.SUCCESS.getCode(), "新增用户成功");
        }
        return DailyAimResult.success(ResultEnum.FAIL.getCode(), "新增用户失败");

    }

    @PutMapping("/updateUser")
    @Operation(summary = "更新用户", description = "更新用户")
    public DailyAimResult<Boolean> updateUser(@RequestBody DailyUsersDTO dailyUsersDTO) throws ParameterException, BusinessException {
        log.info("接口接收到的dailyUsersDTO对象:" + JSON.toJSONString(dailyUsersDTO));
        Optional.ofNullable(dailyUsersDTO).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "dailyUsersDTO对象为空"));
        boolean result = dailyUsersService.updateUser(dailyUsersDTO);
        if (result) {
            return DailyAimResult.success(ResultEnum.SUCCESS.getCode(), "修改用户成功");
        }
        return DailyAimResult.error(ResultEnum.FAIL.getCode(), "修改用户失败");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "删除用户")
    public DailyAimResult<Boolean> deleteUserById(@PathVariable String id) throws ParameterException, BusinessException {
        log.info("接收到的id为:{}", id);
        Optional.ofNullable(id).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "id为空"));
        boolean result = dailyUsersService.deleteUser(id);
        if (result) {
            return DailyAimResult.success(ResultEnum.SUCCESS.getCode(), "删除用户成功");
        }
        return DailyAimResult.error(ResultEnum.FAIL.getCode(), "删除用户失败");
    }

    /**
     * ================针对以后需要批量新增用户，删除用户，修改用户的情况下，进行扩展接口============================
     */

    @PostMapping("/batchAddUser")
    @Operation(summary = "批量新增用户", description = "批量新增用户")
    public DailyAimResult<Boolean> batchAddUser(@RequestBody List<DailyUsersDTO> dailyUsersDTOList) throws ParameterException, BusinessException {
        Optional.ofNullable(dailyUsersDTOList).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "需要新增的用户列表为空!"));
        List<DailyUsers> dailyUsersList = DailyUserConverter.INSTANCE.convertDTOListToEntityList(dailyUsersDTOList);
        try {
            Future<Boolean> isBatchAddUser = dailyUsersService.batchAddUser(dailyUsersList);
            // 等待任务完成并获取结果
            boolean isSuccess = isBatchAddUser.get();
            return isSuccess ? DailyAimResult.success(ResultEnum.SUCCESS.getCode(), "批量新增用户成功") :
                    DailyAimResult.success(ResultEnum.FAIL.getCode(), "批量新增用户失败");
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException("批量新增用户失败", e);
        }
    }

    @DeleteMapping("/batchDeletedUser")
    @Operation(summary = "批量删除用户", description = "批量删除用户")
    public DailyAimResult<Boolean> batchDeletedUser(@RequestBody List<String> dailyUsersIdList) throws ParameterException, BusinessException {
        Optional.ofNullable(dailyUsersIdList).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "需要删除的用户列表为空!"));
        try {
            Boolean isBatchAddUser = dailyUsersService.batchDeletedUser(dailyUsersIdList);
            return DailyAimResult.success(ResultEnum.SUCCESS.getCode(), "批量删除用户成功", isBatchAddUser);
        } catch (Exception e) {
            return DailyAimResult.error(ResultEnum.FAIL.getCode(), e.getMessage());
        }
    }


}
